package server_v2;

import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
import server.Server;

/**
 * @file Server_V2.java
 *
 * @version 0.5
 * @author James Dibble 10009689
 *
 * This Server requires Java 7. Latest Source:
 * http://code.google.com/p/csp-server/source/browse/
 *                                     trunk/Server/src/server_v2/Server_V2.java
 */
public class Server_V2 {

    static Server thisServer;

    /**
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int intPort = -1;
        String strPort = "";
        boolean bolUsedArgsFailed = false;

        Scanner scnrInput = new Scanner(System.in);
        System.out.print("Welcome to File Server V2");
        if (args.length > 0) {
            try {
                strPort = args[0];
            } catch (Exception ex) {
                System.out.println("Usage <Port>");
                bolUsedArgsFailed = true;
            }
        }
        if (!bolUsedArgsFailed && intPort == -1) {
            System.out.print("\nCommand line args can also be used.\n"
                            + "Usage <Port>\n\nPort:"
                            );
            strPort = scnrInput.next();
        }
        try {
            intPort = Integer.parseInt(strPort);
            thisServer = new Server(intPort, Server.Server_Type.FILE_SERVER);
            thisServer.start();
            System.out.println("Server running.  "
                              + "Press 'x' at any time to shutdown the server\n"
                              + "Press 'd' to turn on debug mode"
                              );
            String strInput = "";
            do {
                if ("d".equals(strInput)) {
                    thisServer.toggleDebug();
                }
                strInput = scnrInput.next();
            } while (!"x".equals(strInput));
            try {
                thisServer.KillServer();
            } catch (IOException ex) {
                ex.printStackTrace(System.out);
                System.out.println("General Error.  "
                                  + "Server Shutdown Abnormally.");
            }
        } catch (InputMismatchException imEx) {
            imEx.printStackTrace(System.out);
            System.out.println("Port must be an integer.  Closing..");
        } catch (IOException ioEx) {
            ioEx.printStackTrace(System.out);
            System.out.println("Port is probably in use.  Closing..");
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
            System.out.println("General Error.  Closing..");
        }
    }
}
